package com.yaorange.module.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yaorange.exception.ValidateException;
import com.yaorange.module.system.entity.dto.SysUserQueryDTO;
import com.yaorange.module.system.repository.SysUserRepository;
import com.yaorange.module.system.service.SysUserRoleService;
import com.yaorange.module.system.service.SysUserService;
import com.yaorange.pojo.SysUser;
import com.yaorange.response.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *  用户服务实现类
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private SysUserRoleService sysUserRoleService;


    @Override
    public SysUser findById(Long id) {
        return sysUserRepository.selectById(id);
    }

    @Override
    public void save(SysUser user) {
        sysUserRepository.insert(user);
    }

    @Override
    public void update(SysUser userDetails) {
        if(userDetails.getUserId() == null){
            throw new ValidateException("缺少必要参数，不能修改");
        }
        sysUserRepository.update(userDetails);
    }

    @Override
    public void deleteById(Long id) {
        sysUserRepository.deleteById(id);
    }

    @Override
    public PageResult<SysUser> findAllUsers(SysUserQueryDTO sysUserQueryDTO) {
        // 设置分页参数
        PageHelper.startPage(sysUserQueryDTO.getPageNum(),sysUserQueryDTO.getPageSize());
        // 查询
        List<SysUser> list = sysUserRepository.selectPage(sysUserQueryDTO);
        // 构建分页信息对象
        PageInfo pageInfo = new PageInfo<>(list);
        // 构建pageInfo对象
        PageResult<SysUser> pageResult =(PageResult.builder()
                .total(pageInfo.getTotal())
                .data(pageInfo.getList())
                .build());
        return pageResult;
    }

    @Override
    public void grantRolesList(Long id, List<Long> roleIds) {
        sysUserRoleService.addRelation(id,roleIds);
    }

    @Override
    public List<Long> findRoleListByUserId(Long userId) {
        List<Long> roleIds = sysUserRoleService.getRoleIdByUserId(userId);
        return roleIds;
    }

    @Override
    public SysUser findUserByName(String username) {
        return sysUserRepository.selectByName(username);
    }
}
